from statsmodels.tsa.arima_model import ARIMA
import pandas as pd
import json

import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green.settings")
django.setup()

from green import models
from green.tools import nextDay

dta = [10930, 10318, 10595, 10972, 7706, 6756, 9092, 10551, 9722, 10913, 11151, 8186, 6422,
       6337, 11649, 11652, 10310, 12043, 7937, 6476, 9662, 9570, 9981, 9331]


def arimaPredict(dta, n, p, d, q):
    # dta：数据列表
    # n：向后预测几天
    # p,d,q：arima的三个参数
    dta = pd.Series(dta)
    model = ARIMA(dta, (p, d, q)).fit()
    # print("arima预测结果：")
    res = model.forecast(n)[0]

    # print(res)
    model.forecast(n)
    return res


def initTwoPredict():
    with open("../templates/two/showTwo.json", 'r', encoding='UTF-8') as f:
        load_dict = json.load(f)
    CO2_data = []
    lastDay = load_dict['data'][len(load_dict['data']) - 1]['time']
    for item in load_dict['data']:
        CO2_data.append(item['MtCO2'])
    # 取后面24个元素作为新列表
    CO2_data = CO2_data[-24:]
    # 预测得到一个列表
    preList = arimaPredict(CO2_data, 7, 0, 1, 1)
    preList = [(i) for i in preList]

    print(preList)
    lastDateList = lastDay.split('-', 2)
    lastDateDict = {'year': lastDateList[0], 'month': lastDateList[1], 'day': lastDateList[2]}

    for item in preList:
        # lastTimeId = lastTimeId + 1
        lastDateDict = nextDay(int(lastDateDict['year']), int(lastDateDict['month']), int(lastDateDict['day']))
        oneData = {
            'time': str(lastDateDict['year']) + '-' + str(lastDateDict['month']) + '-' + str(lastDateDict['day']),
            'MtCO2': item}
        load_dict['data'].append(oneData)

    s = json.dumps(load_dict)
    f = open('../templates/two/predict_new.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()

    #     向后预测七天的内容，写回文件到predict.json
    return


if __name__ == '__main__':
    initTwoPredict()
    # arimaPredict(dta, 1, 0, 1, 1)
